// 引入 react 依赖
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Text, View, Image, TouchableOpacity, ImageBackground, ScrollView, InteractionManager } from 'react-native';
import * as ActionTypes from '../../constants/constants.js';

// 引入第三方依赖
import _ from 'lodash';
import pureRender from 'pure-render-decorator';
import { Actions } from 'react-native-router-flux';
import Icon from 'react-native-vector-icons/FontAwesome';

// antd 按需加载
import { Tabs, Toast, Portal, List, Switch, Checkbox, WhiteSpace } from '@ant-design/react-native';
const Item = List.Item;
const Brief = Item.Brief;
const CheckboxItem = Checkbox.CheckboxItem;

// 引入 处理数据 所需文件
import { orderConfirm, orderSubmit } from '../../module/module.js'

// 引入样式
import Style from './style/style.js';

// 引入公用组件
import { Status, NavBar, CacheImage, Layout } from '../../components/index.js'

// 引入专用组件
import { } from './components'

// 引入工具包
import { background } from '../../util/images.js'
import { press, size, ScreenWidth, pathHead, defaultDataList, onEndReached, onRefresh, concatDataList, defaultPage } from '../../util/utils.js'

class SubmitOrder extends Component {

  constructor(props) {
    super(props)
    this.state = {
      goodsInfo: {},
      openInvoice: 0, // 是否开发票：0不开发票，1开发票
    }
  }

  componentDidMount() {
    const { dispatch, goodsList, submitOrderAddress, defaultInvoice, submitOrderInvoice, defaultAddres } = this.props
    this.loading = Toast.loading('加载中')

    // app打开首次进此页面
    if (!submitOrderAddress.id) {
      dispatch({
        type: ActionTypes.setSubmitOrderAddress,
        data: defaultAddres
      })
    }

    // 是否默认选择发票信息
    // // app打开首次进此页面
    // if (!submitOrderInvoice.id) {
    //   dispatch({
    //     type: ActionTypes.setSubmitOrderInvoice,
    //     data: defaultInvoice
    //   })
    // }

    orderConfirm({ goodsList }).then(res => {
      Portal.remove(this.loading)
      this.setState({
        goodsInfo: res.data
      })
    }).finally(() => {
      Portal.remove(this.loading)
    })
  }

  componentWillReceiveProps(props) {
    if (props.submitOrderInvoice.id) {
      this.setState({
        openInvoice: 1
      })
    } else {
      this.setState({
        openInvoice: 0
      })
    }
  }

  handleRrderSubmit() {
    const { submitOrderAddress, submitOrderInvoice, goodsList, goodType } = this.props
    const { goodsInfo, openInvoice } = this.state
    if (!submitOrderAddress.id) {
      Toast.info('请选择地址', 1)
      return
    }
    this.loading = Toast.loading('提交订单中...', 0)
    let option = {
      deliveryAddressId: submitOrderAddress.id,
      goodsList: goodsList,
      orderNote: '',
      openInvoice
    }
    if (option.openInvoice == 1) {
      option.invoiceId = submitOrderInvoice.id
    }
    if (goodType && goodType == 1) {
      // orderAgentSubmit(option).then(res => {
      //   Portal.remove(this.loading)
      //   Toast.success(res.message, 1)
      //   Actions.selectPay({ ...res.data, totalMoney: goodsInfo.totalMoney })
      //   // Actions.paymentResult()
      // })
    } else {
      orderSubmit(option).then(res => {
        Portal.remove(this.loading)
        Toast.success(res.message, 1)
        Actions.selectPay({ ...res.data, totalMoney: goodsInfo.totalMoney })
        // Actions.paymentResult()
      }).finally(() => {
        Portal.remove(this.loading)
      })
    }
  }

  renderGoodsInfo() {
    const { goodsInfo } = this.state
    const { submitOrderInvoice, defaultAddres } = this.props
    if (goodsInfo && goodsInfo.totalMoney) {
      return (
        <View style={{}}>
          <View style={{
            backgroundColor: '#fff',
            borderRadius: 6,
            overflow: 'hidden',
            borderWidth: 0,
            borderTopWidth: .5,
            borderBottomWidth: .5,
            borderColor: '#D9D9D9'
          }}>
            <View style={{
            }}>
              <TouchableOpacity>
                <View style={{
                  flexDirection: 'row',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                  paddingHorizontal: 15
                }}>
                  <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 32, }}>商品信息</Text>
                  <Icon name="angle-right" size={14} color={'#61676F'} />
                </View>
              </TouchableOpacity>
            </View>
            <View style={{ height: .5, backgroundColor: '#D9D9D9' }}></View>
            {goodsInfo.goodsList.map((item, index) => (
              <View
                key={index}
                style={{
                  flexDirection: 'row',
                  padding: 15
                }}
              >
                <View style={{
                  width: 80,
                }}>
                  <CacheImage
                    resizeMod={"contain"}
                    style={{
                      width: 80,
                      height: 80,
                    }}
                    source={{ uri: `${pathHead}${item.goodsMainPic}` }}

                  />
                </View>
                <View style={{
                  flexDirection: 'column',
                  justifyContent: 'space-between',
                  height: 80,
                  marginLeft: 10,
                  flex: 1
                }}>
                  <Text style={{ fontSize: 16, color: '#000', lineHeight: 18, }} numberOfLines={1} ellipsizeMode={'tail'}>{item.goodsName}</Text>
                  <Text style={{ fontSize: 12, color: '#61676F', lineHeight: 16, }} numberOfLines={1} ellipsizeMode={'tail'}>{item.goodsAttribute}</Text>
                  <View style={{
                    flexDirection: 'row',
                    justifyContent: 'space-between',
                    alignItems: 'center',
                  }}>
                    <Text style={{ fontSize: 14, color: '#E5C67B', lineHeight: 30, }}>¥{item.goodsPrice}</Text>
                    <Text style={{ fontSize: 12, color: '#61676F', lineHeight: 16, }}>x{item.goodsNumber}</Text>
                  </View>
                </View>
              </View>
            ))}
          </View>
          <View style={{}}>
            {/* <List renderHeader="使用分身币">
              <Item extra={
                <View style={{ flexDirection: 'row', alignItems: 'center', }}>
                  <Switch checked />
                  <Brief style={{ textAlign: 'right' }}>使用200分身币可抵扣¥2.00现金</Brief>
                </View>
              } arrow="empty">分身币</Item>
            </List> */}
            <List renderHeader="合计">
              <Item extra={`¥${goodsInfo.totalMoney}`} arrow="empty">商品合计</Item>
              <Item extra={`${goodsInfo.totalCv}`} arrow="empty">CV</Item>
              <Item extra={`¥${goodsInfo.postage}`} arrow="empty">运费</Item>
              <Item extra={`${goodsInfo.totalCoin}`} arrow="empty">分身币抵扣</Item>
              {/* <Item extra="¥0.00" arrow="empty">活动优惠</Item> */}
            </List>


            <List renderHeader="发票信息">
              {submitOrderInvoice && submitOrderInvoice.id && (
                <TouchableOpacity
                  onPress={() => {
                    Actions.invoice({ method: 'select' })
                  }}
                >
                  <View style={{
                    flexDirection: 'row',
                    alignItems: 'center',
                    backgroundColor: '#fff',
                    padding: 15
                  }}>
                    <View style={{
                      flex: 1
                    }}>
                      <View style={{
                        flexDirection: 'row',
                        alignItems: 'center',
                        marginBottom: 8
                      }}>
                        <Text style={{ fontSize: 16, color: '#8B8B8D', lineHeight: 18, marginRight: 15 }}>{submitOrderInvoice.name}</Text>
                        <Text style={{ fontSize: 16, color: '#8B8B8D', lineHeight: 18, marginRight: 15 }}>{submitOrderInvoice.taxNumber}</Text>
                      </View>
                      <View style={{
                        flexDirection: 'row',
                        alignItems: 'center',
                      }}>
                        {submitOrderInvoice.id && submitOrderInvoice.id == defaultAddres.id && (
                          <View style={{ backgroundColor: '#E5C67B', paddingVertical: 3, paddingHorizontal: 8, borderRadius: 4, marginRight: 15 }}>
                            <Text style={{ fontSize: 12, color: '#fff', }}>默认</Text>
                          </View>
                        )}
                        <Text style={{ fontSize: 14, color: '#61676F', marginRight: 12, flex: 1 }}>{submitOrderInvoice.regAddress}</Text>
                      </View>
                    </View>
                    <Icon name="angle-right" size={20} color={'#000'} />
                  </View>
                </TouchableOpacity>
              )}
              {!submitOrderInvoice.id && (
                <TouchableOpacity
                  onPress={() => {
                    Actions.invoice({ method: 'select' })
                  }}
                >
                  <View style={{
                    flexDirection: 'row',
                    alignItems: 'center',
                    backgroundColor: '#fff',
                    padding: 15
                  }}>
                    <View style={{
                      flex: 1
                    }}>
                      <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, textAlign: 'left' }}>请选择发票信息</Text>
                    </View>
                    <Icon name="angle-right" size={20} color={'#000'} />
                  </View>
                </TouchableOpacity>
              )}
            </List>

            {/* <List renderHeader="支付方式">
              <CheckboxItem
                checked={true}
                onChange={event => {
                  // this.setState({ checkboxItem1: event.target.checked });
                }}
              >微信支付</CheckboxItem>
            </List> */}
            <WhiteSpace />
          </View>
          <WhiteSpace />
        </View>
      )
    }
    return null
  }

  render() {
    const { goodsInfo } = this.state
    const { defaultInvoice, submitOrderAddress } = this.props
    return (
      <Layout
        style={{ backgroundColor: '#fff' }}
        header={<Status />}
        footer={
          <View style={{
            flexDirection: 'row',
            alignItems: 'center',
          }}>
            <View style={{
              height: 52,
              alignItems: 'center',
              flexDirection: 'row',
              flex: 1,
              paddingLeft: 15
            }}>
              <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, marginLeft: 15 }}>应付金额：￥{goodsInfo && goodsInfo.totalMoney && (goodsInfo.totalMoney)}</Text>
            </View>
            <TouchableOpacity
              style={{
                height: 52,
                width: ScreenWidth / 3,
                backgroundColor: '#000000'
              }}
              onPress={() => {
                this.handleRrderSubmit()
              }}>
              <Text style={{ fontSize: 14, color: '#fff', lineHeight: 52, textAlign: 'center' }}>提交订单</Text>
            </TouchableOpacity>
          </View>
        }
      >
        <NavBar
          title="提交订单"
          back={true}
        />
        <ScrollView style={Style.content}>
          {submitOrderAddress && submitOrderAddress.id && (
            <TouchableOpacity
              onPress={() => {
                Actions.address({ method: 'select' })
              }}
            >
              <View style={{
                flexDirection: 'row',
                alignItems: 'center',
                backgroundColor: '#fff',
                padding: 15
              }}>
                <View style={{
                  flex: 1
                }}>
                  <View style={{
                    flexDirection: 'row',
                    alignItems: 'center',
                    marginBottom: 8
                  }}>
                    <Text style={{ fontSize: 16, color: '#8B8B8D', lineHeight: 18, marginRight: 15 }}>{submitOrderAddress.consignee}</Text>
                    <Text style={{ fontSize: 16, color: '#8B8B8D', lineHeight: 18, marginRight: 15 }}>{submitOrderAddress.phone}</Text>
                  </View>
                  <View style={{
                    flexDirection: 'row',
                    alignItems: 'center',
                  }}>
                    {submitOrderAddress.id && submitOrderAddress.id == defaultInvoice.id && (
                      <View style={{ backgroundColor: '#E5C67B', paddingVertical: 3, paddingHorizontal: 8, borderRadius: 4, marginRight: 15 }}>
                        <Text style={{ fontSize: 12, color: '#fff', }}>默认</Text>
                      </View>
                    )}
                    <Text style={{ fontSize: 14, color: '#61676F', marginRight: 12, flex: 1 }}>{submitOrderAddress.fullAddress}</Text>
                  </View>
                </View>
                <Icon name="angle-right" size={20} color={'#000'} />
              </View>
            </TouchableOpacity>
          )}
          {!submitOrderAddress.id && (
            <TouchableOpacity
              onPress={() => {
                Actions.address({ method: 'select' })
              }}
            >
              <View style={{
                flexDirection: 'row',
                alignItems: 'center',
                backgroundColor: '#fff',
                padding: 15
              }}>
                <View style={{
                  flex: 1
                }}>
                  <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, textAlign: 'center' }}>请选择收货地址</Text>
                </View>
                <Icon name="angle-right" size={20} color={'#000'} />
              </View>
            </TouchableOpacity>
          )}
          <Image resizeMode='repeat' resizeMethod='scale' style={{ width: ScreenWidth, height: 5 }} source={require('../../static/images2/select-address.png')} />
          <View style={{ height: 10, backgroundColor: '#e8e8ed' }} />
          {this.renderGoodsInfo()}
        </ScrollView>
      </Layout>
    );
  }
}


export default connect(({ user, defaultAddres, defaultInvoice, submitOrderAddress, submitOrderInvoice }) => ({
  user, defaultAddres, defaultInvoice, submitOrderAddress, submitOrderInvoice
}))(pureRender(SubmitOrder))
